<?php
namespace StarCloud\Library;

use Framework\DiServices\HttpClient;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use Phalcon\Di;
use StarCloud\Library\Exception;

class Captcha
{
    /* @var $httpClient HttpClient */
    private $httpClient;
    private $username = "fengshuang110";
    private $password = "Fengshuang@996";
    private $__VIEWSTATE = '';
    private $__VIEWSTATEGENERATOR = '';
    private $type = 3; // ctl00$rblSaleType
    private $productId = 'AAJSUPHNZG010CZ';

    private $header = [
        'Content-Type' => 'application/json',
    ];
    use HttpCurl;
    private $client = null;
    public function __construct()
    {
        $cookieJar = new CookieJar();
        $this->client = new Client([
            'cookies' => $cookieJar
        ]);
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }
    // 伪造表单

    public function postForm($code, $cate, $productId, $cardNo, $cardPwd)
    {
        $url = 'https://junka.com/Official/JNetMapSup/CommonCharge.aspx?category='.$cate.'&product=AAJSUPHNZG200CZ';
        $formData = [
            '__EVENTTARGET' => '',
            '__EVENTARGUMENT' => '',
            '__LASTFOCUS' => '',
            '__VIEWSTATE' => $this->__VIEWSTATE,
            '__VIEWSTATEGENERATOR' => $this->__VIEWSTATEGENERATOR,
            '__VIEWSTATEENCRYPTED' => '',
            'ctl00$rblSaleType' => $this->type,
            'ctl00$cboProductList' => $productId,
            'ctl00$cboProductNum' => 1,
            'ctl00$hidCardPwdSign' => '',
            'ctl00$junUCard$UCardType' => 'OneUCardType',
            'ctl00$junUCard$FirstUCardNo' => $cardNo,
            'ctl00$junUCard$FirstUCardPassword' => $cardPwd,
            'ctl00$junUCard$SecondUCardNo' => '',
            'ctl00$junUCard$SecondUCardPassword' => '',
            'ctl00$junUCard$ThirdUCardNo' => '',
            'ctl00$junUCard$ThirdUCardPassword' => '',
            'ctl00$MiddleTemplate$hidFromType' => '',
            'ctl00$MiddleTemplate$hidCategory' => $cate,
            'ctl00$MiddleTemplate$hidRegionName' => '',
            'ctl00$MiddleTemplate$hidRegionValue' => '',
            'ctl00$MiddleTemplate$hidServerName' => '',
            'ctl00$MiddleTemplate$hidServerValue' => '',
            'ctl00$MiddleTemplate$junCharge$txtUserAccount' => '93669482',
            'ctl00$MiddleTemplate$junCharge$txtUserAccountOk' => '93669482',
            'ctl00$MiddleTemplate$txtRandomCode' => $code,
            'ctl00$MiddleTemplate$btnChargeOK' => '立即充值',
            'ctl00$txtRealityUserName' => '',
            'ctl00$txtRealityIDCard' => '',
            'ctl00$txtEmail' => '',
        ];
        try {
            $response = $this->client->request('POST', $url, [
                'form_params' => $formData,
                'header' => [
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ]
            ]);
            var_dump($response->getBody()->getContents());
            var_dump($response->getStatusCode());
            var_dump($formData);
        }catch (\Exception $e) {
            var_dump($e->getMessage(), $e->getCode(), $e->getTraceAsString());
        }

    }

    public function deCaptcha($baseImg)
    {
        $url = 'http://www.fdyscloud.com.cn/tuling/predict';
        $body = [
            "username" => $this->username,
            "password" => $this->password,
            "b64" => $baseImg,
            "ID" => "04897896",
            "version" => "3.1.1"
        ];
        var_dump($body);

        $response = $this->httpClient->sendPostRequest($url, $body);
        $json = json_decode($response->getBody()->getContents(), true);

        var_dump($json);
        if (isset($json['code']) && $json['code'] == 1) {
            return $json['data']['result'];
        } else {
           throw new Exception(9999, "错误原因：图片base64转码错误，上传数据不符合base64规范，请检查！");
        }
    }

    public function getHeader()
    {
        return $this->header;
    }

    public function getProductInfo()
    {
        $url = "https://junka.com/Official/JNetMapSup/CommonCharge.aspx?category=AAJSUPHNZG&product=AAJSUPHNZG010CZ";
        $response = $this->client->request('GET', $url);

        $htmlContent = $response->getBody()->getContents();
        preg_match('/<input .*?name="__VIEWSTATE".*?value="(.*?)"/', $htmlContent, $matches);

        $this->__VIEWSTATE = $matches[1];

        preg_match('/<input .*?name="__VIEWSTATEGENERATOR".*?value="(.*?)"/', $htmlContent, $matches1);

        $this->__VIEWSTATEGENERATOR = $matches1[1];

        $captchaUrl = 'https://junka.com/Modules/RandomImage.aspx?ran=' . mt_rand(10000000, 99999999);

        $response1 = $this->client->request('GET', $captchaUrl);

        $code = $this->deCaptcha(base64_encode($response1->getBody()->getContents()));

        $this->postForm($code, 'AAJSUPHNZG', 'AAJSUPHNZG010CZ', '2403152749867137', '7019100113148252');
    }
}